<?php

class Store_Form_Store extends YouNet_Form
{
	const FANPAGE_NAME		= 'fanpages';
	const UNIT_CODE			= 'unit_code';
	const STORE_LAYOUT		= 'store_layout';
	const DEFAULT_LAYOUT	= 'default_layout';
	
	const LAYOUT_3x12		= 1;
	const LAYOUT_4x16		= 2;
	const LAYOUT_10xLIST	= 4;
	const LAYOUT_3xAll		= 8;
	
	protected $_storeRow = null;
	protected $_cancelUrl = '';
	protected $_downloadCssUrl = '';
	
	protected $_element_decorators = array(
		'ViewHelper',
		'Description',
		'Errors',
		array('HtmlTag', array('tag' => 'dd')),
		array('Label', array('tag' => 'dt')),
	);
	protected $_file_decorators = array(
		'File',
		'Description',
		'Errors',
		array('HtmlTag', array('tag' => 'dd')),
		array('Label', array('tag' => 'dt')),
	);

	public function __construct(array $options = null)
	{
		if (!empty($options) && isset($options['store']))
		{
			if ($options['store'] instanceof Core_Model_Store)
			{
				$this->_storeRow = $options['store'];
			}
		}
		parent::__construct();
	}

	public function init()
	{
		parent::init();
		$this->setAttrib('class', 'sm_form classic');
		$this->setName('store-form');

		$this->_initFanpage();

		$this->addElement('text', 'name', array(
			'label' => 'STORE_NAME',
			'required' => true,
			'filters' => array('StringTrim')
		));

		$this->getElement('name')->addValidator('stringLength', false, array(0, 255));

		$this->addElement('RichEditor', 'description', array(
			'label' => 'STORE_DESCRIPTION',
			'rows' => '3'
		));
        
		$this->_initSystemCategory();

		$this->addElement('text', 'google_analytics_id', array(
			'label' => 'GOOGLE_ANALYTICS_ID',
			'required' => false,
			'filters' => array('StringTrim'),
			'description' => 'HINT_GOOGLE_ANALYTICS_ID'
		));
		$this->getElement('google_analytics_id')->addValidator('regex', true, array('/^[A-Za-z0-9\-]+$/'))
				->addErrorMessage('ERROR_UNACCEPTABLE_GOOGLE_ANALYTICS_ID');
        
        $this->addElement('checkbox', 'is_allow_comment', array(
			'label' => 'STORE_COMMENT_SETTING',
            'description' => 'STORE_COMMENT_SETTING_HINT',
            'value' => Core_Model_DbTable_Stores::STATUS_ALLOW_COMMENT
		));
		
        $this->addElement('text', 'notify_email', array(
			'label'		=> 'LABEL_NOTIFY_EMAIL',
			'required'	=> false,
			'filters'	=> array('StringTrim'),
            'description' => 'HINT_NOTIFY_EMAIL'
		));
        $this->getElement('notify_email')->getDecorator('Label')->setOption('escape', false);
        $this->getElement('notify_email')->addValidator('regex', true, array('/^[\w\d\-\_\.]+\@([\w\d\-]+\.){1,2}[\w\d]+(\s*\,\s*[\w\d\-\_\.]+\@([\w\d\-]+\.){1,2}[\w\d]+)*$/'))
                ->addErrorMessage('ERROR_UNACCEPTABLE_NOTIFY_EMAIL');

		$this->_initCurrencyUnit();
        
        $this->addElement('multiCheckbox', 'shopping_cart_setting', array(
			'label' => 'LABEL_SHOPPING_CART_SETTING',
			'multiOptions' => array(
                Core_Model_DbTable_Stores::STATUS_SHOPPING_CART_SETTING => 'DESCRIPTION_SHOPPING_CART_SETTING'
            ),
            'value' => array(
                Core_Model_DbTable_Stores::STATUS_SHOPPING_CART_SETTING
            )
		));
		
		$this->addElement('text', 'purchase_info', array(
			'label' => 'STORE_PURCHASE_DEFAULT',
			'required' => false,
			'filters' => array('StringTrim')
		));
		$this->getElement('purchase_info')->getDecorator('Label')->setOption('escape', false);
		$this->getElement('purchase_info')->getDecorator('Description')->setOption('escape', false);
		$this->getElement('purchase_info')->setDescription('STORE_PURCHASE_DEFAULT_DESCRIPTION');
		$this->getElement('purchase_info')->addValidator('stringLength', false, array(0, 255));
        
        $this->addElement('RichEditor', 'purchase_instruction', array(
			'label' => 'STORE_PURCHASE_INSTRUCTION',
			'rows' => '3'
		));

        $this->_initLanguage();
		
		$this->addElement(new YouNet_Form_Element_File('banner_image', array(
					'decorators' => $this->_file_decorators,
					'label' => 'BANNER_IMAGE'
				)));

		$this->banner_image->setDestination(UPLOAD_PATH . '/' . STORE_IMAGE_FOLDER);
		// ensure only 1 file
		$this->banner_image->addValidator('Count', false, 1);
		// limit to 100K
		$this->banner_image->addValidator('Size', false, 204800 * 5);
		// only JPEG, PNG, and GIFs
		$this->banner_image->addValidator('Extension', false, 'jpg,png,gif,jpeg');
		$this->banner_image->setDescription(sprintf(
						$this->getTranslator()->translate('IMAGE_UPLOAD_BANNER_HINT'), '1 MB', FANPAGE_MAX_WIDTH . 'px'
				));
		$this->banner_image->setRequired(false);
		$this->banner_image->getValidator('Upload')->setMessage(
				$this->getTranslator()->_('ERROR_STORE_BANNER_IMAGE_IS_NO_FILE'), Zend_Validate_File_Upload::NO_FILE
		);

		$this->addElement('text', 'link', array(
			'label' => 'BANNER_LINK',
			'filters' => array('StringTrim')
		));
		$this->link->addValidator(new Core_Validate_Uri());

		$maxLengthValidator = new Zend_Validate_StringLength(array('max' => 255));
		$maxLengthValidator->setMessage('ERROR_BANNER_LINK_IS_TOO_LONG', Zend_Validate_StringLength::TOO_LONG);
		$this->link->addValidator($maxLengthValidator);
        
		$this->_initStoreLayout();
		$this->_initCustomCss();
		
		$this->_initButtons();
	}
	private function _initLanguage()
	{
		$this->addElement('select', 'language', array(
			'label' => 'STORE_LANGUAGE',
			'multioptions' => Core_Model_DbTable_Stores::getListSupportedLanguage()
		));
		$this->getElement('language')->getDecorator('Label')->setOption('escape', false);
	}
	private function _initCustomCss()
	{
		$this->addElement(new YouNet_Form_Element_File('css', array(
			'decorators' => $this->_file_decorators,
			'label' => 'CSS_FILE'
		)));
		$this->css->setDestination(UPLOAD_PATH . '/' . STORE_CSS_FOLDER);
		$this->css->addValidator('Extension', false, 'css');
		$this->css->addValidator('Count', false, 1);
		$this->css->addValidator('Size', false, 204800);
		$this->css->setDescription(sprintf(
				$this->getTranslator()->translate('CSS_UPLOAD_FILE_HINT'), '200 Kb'
		));
		$this->css->getDecorator('Label')->setOption('escape',false);
	}
	private function _initSystemCategory()
	{
		if (isset($_POST['id_system_category']))
		{
			$id_parent = NULL;
			$is_first = true;
			foreach ($_POST['id_system_category'] as $key => $value)
			{
				$this->_addSystemCategoryWidget($key, $id_parent, false, $value);
				$id_parent = $value;
				$is_first = false;
			}
			$this->addDisplayGroup(
					array_keys($_POST['id_system_category']), 'id_system_category'
			);
		}
		else
		{
			if (!$this->hasStore() || !$this->_storeRow->getSystemCategory())
			{
				$key = 'system_category_1';
				$this->_addSystemCategoryWidget($key, NULL, false, '');

				$this->addDisplayGroup(
						array($key), 'id_system_category'
				);
			}
			else
			{
				$id_parent = NULL;
				$is_first = true;
				$arrGroupElements = array();

				$arrIdCategories = $this->_storeRow
						->getSystemCategory()
						->getHierarchyIdCategories();
				foreach ($arrIdCategories as $id)
				{
					$key = 'system_category_' . $id;
					$this->_addSystemCategoryWidget($key, $id_parent, false, $id);
					$is_first = false;
					$id_parent = $id;
					$arrGroupElements[] = $key;
				}

				$this->addDisplayGroup(
						$arrGroupElements, 'id_system_category'
				);
			}
		}
		$this->id_system_category->getDecorator('DtDdWrapper')->setOption('escape', false);
		$this->id_system_category->getDecorator('DtDdWrapper')->setOption(
				'dtLabel', '<label class="">' . $this->getTranslator()->translate('STORE_SYSTEM_CATEGORY') . '</label>'
		);
	}

	private function _initStoreLayout()
	{
		$this->addElement('multiCheckbox', self::STORE_LAYOUT, array(
			'label' => 'LABEL_STORE_LAYOUT',
			'required'=> true,
			'multiOptions' => Core_Model_DbTable_Stores::getLayoutOptions()
		));

		$this->getElement(self::STORE_LAYOUT)->getDecorator('Label')->setOption('escape', false);
		
		$this->addElement('select', self::DEFAULT_LAYOUT, array(
			'label' => 'LABLE_DEFAULT_LAYOUT',
			'required'=> true,
			'multiOptions' => array('' => '- select -') + Core_Model_DbTable_Stores::getLayoutOptions()
		));
	}

	private function _addSystemCategoryWidget($key, $id_parent, $required, $value)
	{
		$arrAttributes = array(
			'label' => NULL,
			'required' => true,
			'class' => 'system_category',
			'belongsTo' => 'id_system_category'
		);
		$options = array('' => YouNet_Util::translate('SELECT')) + Core_Model_DbTable_Category_Systems::getArrCategories($id_parent);
		$this->addElement('select', $key, array_merge(
				$arrAttributes, array(
				'multiOptions' => $options,
				'required' => $required,
				'value' => $value
			)
		));
		$this->$key->removeDecorator('Label');
	}

	private function _initButtons()
	{
		$this->addElement('submit', 'submit', array(
			'label' => 'BUTTON_SAVE',
			'onclick' => 'window.isSubmitting = true;',
			'class' => 'greenbutton spacing'
		));
		$this->addElement('submit', 'cancel', array(
			'label' => 'BUTTON_CANCEL',
			'onclick' => 'window.isSubmitting = false;',
			'class' => 'graybutton'
		));
		$this->submit->removeDecorator('Label');
		$this->cancel->removeDecorator('Label');
		$this->submit->removeDecorator('HtmlTag');
		$this->cancel->removeDecorator('HtmlTag');

		$this->addDisplayGroup(array('submit', 'cancel'), 'group-btn');
	}

	private function _initCurrencyUnit()
	{
		$this->addElement('Select', self::UNIT_CODE, array(
			'label' => 'UNIT_CODE',
			'required'=>true
		));
		$listCurrency = Core_Model_DbTable_CurrencyUnits::getInstance()->getAssocListCurrency();
		$this->getElement(self::UNIT_CODE)->setMultiOptions($listCurrency);
		$this->getElement(self::UNIT_CODE)->setValue(DEFAULT_CURRENCY);
	}

	private function _initFanpage()
	{
		$this->addElement('MultiCheckbox', self::FANPAGE_NAME, array(
			'label' => 'FANPAGES',
		));
		$this->getElement(self::FANPAGE_NAME)->setRequired(true);
		$this->getElement(self::FANPAGE_NAME)->setMultiOptions($this->_social->getPageList());
		$this->getElement(self::FANPAGE_NAME)->setDecorators(array(array('ViewScript', array(
					'viewScript' => 'decorator/load_my_fanpages.phtml',
			))));
	}

	public function fill(Core_Model_Store $storeRow)
	{
		$this->_storeRow = $storeRow;
		$values = $storeRow->toArray();
		$layout_values = Core_Model_DbTable_Stores::getArrayLayouts($storeRow->layout);
		
		$layout_disabled_options = array_diff(array_keys(Core_Model_DbTable_Stores::getLayoutOptions()),$layout_values);
		
		$values[self::STORE_LAYOUT] = $layout_values;
		unset($values['id_system_category']);
		
		$this->populate(array_merge($values, array(self::FANPAGE_NAME => $storeRow->getArrIdPages(), 'shopping_cart_setting' => array($storeRow->shopping_cart_setting))));
		$this->getElement(self::DEFAULT_LAYOUT)->setAttrib('disable', $layout_disabled_options);
	}
	
	private function _updatePreviousImage(Core_Model_Store $storeRow)
	{
		if (!empty($storeRow->banner_image))
		{
			$description = $this->banner_image->getDescription();

			$description .= '<span>';
			$description .= '<input type="hidden" name="is_delete_banner"/>';
			$description .= '<img src="' . $storeRow->getBannerImageUrl() . '"/>';
			$description .= '<span class="btn_delete">delete</span>';
			$description .= '</span>';

			$this->banner_image->setDescription($description);
			$this->banner_image->getDecorator('Description')->setOption('escape', false);
		}
	}

	public function getBannerImageName()
	{
		return $this->_getImageNameAndReceive('banner_image');
	}

	public function getFanpageCssName()
	{
		$cssElement = $this->css;
		$ret_name = '';
		if (!empty($cssElement))
		{
			$css_name = $cssElement->getFileName(null, false);
			if(!empty($css_name))
			{
				$max_file_name_length = MAX_FILENAME_LENGTH - 16;
				
				if (strlen($css_name) > $max_file_name_length)
				{
					$css_name = substr($css_name, -$max_file_name_length);
				}
				$ret_name	=	time() . '_' . mt_rand(0, 9999) . '_' . preg_replace('/[^A-Za-z0-9-_.]/', '', $css_name);
				$target		=	UPLOAD_PATH . '/' . STORE_CSS_FOLDER . '/';
				$target		.=	$ret_name;
				$cssElement->addFilter('Rename', array(
					'target'	=>$target
				));
				$cssElement->receive();
			}
		}
		return $ret_name;
	}
	private function _updatePreviousCssFile(Core_Model_Store $storeRow)
	{
		if (!empty($storeRow->css))
		{
			$description = $this->css->getDescription();

			$description .= '<span>';
			$description .= '<input type="hidden" name="is_delete_css"/><a href="' . $this->_downloadCssUrl . '" target="_blank"><span class="text">';
			$description .= $this->getTranslator()->translate('SKIN_NAME') . '</span></a><span class="text"> - </span>';
			$description .= '<span class="delete inline_delete">delete</span>';
			$description .= '</span>';		
			$this->css->setDescription($description);
			$this->css->getDecorator('Description')->setOption('escape', false);
		}
	}
	
	private function _getImageNameAndReceive($name)
	{
		$ret_name = '';
		/* @var $imageElement Zend_Form_Element_File */
		$imageElement = $this->$name;
		if (!empty($imageElement))
		{
			$image_name = $imageElement->getFileName(null, false);
			if (!empty($image_name))
			{
				/* max length: MAX_FILENAME_LENGTH + 10 + [1,4] */
				$max_file_name_length = MAX_FILENAME_LENGTH - 16;

				if (strlen($image_name) > $max_file_name_length)
				{
					$image_name = substr($image_name, -$max_file_name_length);
				}
				$ret_name = time() . '_' . mt_rand(0, 9999) . '_' . preg_replace('/[^A-Za-z0-9-_.]/', '', $image_name);
				$target = UPLOAD_PATH . '/' . STORE_IMAGE_FOLDER . '/';
				$thumbnail = UPLOAD_PATH . '/' . STORE_IMAGE_FOLDER . '/' . THUMBNAIL_IMAGE_FOLDER . '/';

				$target .= $ret_name;
				$thumbnail .= $ret_name;

				$imageElement->addFilter('Rename', array(
					'target' => $target
				));

				if ($imageElement->receive())
				{
					if ($name == 'banner_image')
					{
						$this->_cropImage($target, $thumbnail);
					}
				}
			}
		}
		return $ret_name;
	}

	protected function _cropImage($source, $target)
	{
		Core_Util::createThumbnail($source, $target, Core_ImageUtil::DEFAULT_BANNER_THUMBNAIL_SIZE);
	}

	public function isValid($data)
	{
		$isValid = parent::isValid($data);
		
		$layouts = isset($data[self::STORE_LAYOUT]) ? $data[self::STORE_LAYOUT] : array();
		
		if(!empty($layouts))
		{
			$layout_disabled_options = array_diff(array_keys(Core_Model_DbTable_Stores::getLayoutOptions()), $layouts);
			$this->getElement(self::DEFAULT_LAYOUT)->setAttrib('disable', $layout_disabled_options);
		}
		else
		{
			$this->getElement(self::DEFAULT_LAYOUT)->setAttrib('disable', array_keys(Core_Model_DbTable_Stores::getLayoutOptions()));
		}
		
		if(!empty($data[self::DEFAULT_LAYOUT]))
		{
			if (!in_array($data[self::DEFAULT_LAYOUT], $layouts))
			{
				$msg = $this->getTranslator()->_('MSG_DEFAULT_LAYOUT_MUST_BE_CHECKED_IN_LAYOUT_SET');
				$this->getElement(self::DEFAULT_LAYOUT)->addError($msg);
				$isValid = false;
			}
		}
		
		if (!empty($data['fanpages']) && $this->_storeRow->isShown())
		{
			$arrIdPages = YouNet_Api::getInstance()->getSocialPlugin()->getUserPageIds();
			if (!empty($this->_storeRow->id))
			{
				/** use to diable those fanpage has a published store */
				$arrIdPages = array_diff($arrIdPages, $this->_storeRow->getArrIdPages());
				if( !empty($arrIdPages) )
				{
					$rowPublishedPages = Core_Model_DbTable_Pages::getInstance()->getPublishedStores($arrIdPages);
					if (!empty($rowPublishedPages))
					{
						$arrDisabledOptions = explode(',', $rowPublishedPages->id_pages);
						$arrInvalid = array_intersect($arrDisabledOptions, $data['fanpages']);
						if ($arrInvalid)
						{
							$msg = $this->getTranslator()->_('MSG_MUST_BE_NO_PUBLISHED_STORE') . $this->_proccessError($arrInvalid);
							$this->getElement(self::FANPAGE_NAME)->addError($msg);
							$isValid = false;
						}
					}
				}
			}
		}
		return $isValid;
	}

	private function _proccessError($idPages)
	{
		$arrAssocIdPages = array();
		$arrPageList = YouNet_Api::getInstance()->getSocialPlugin()->getPageList();

		foreach ($idPages as $id_page)
		{
			$arrAssocIdPages[] = $arrPageList[$id_page];
		}

		return $this->_proccessErrorMessage($arrAssocIdPages);
	}

	private function _proccessErrorMessage($arrMsg)
	{
		$size = sizeof($arrMsg);
		if ($size == 1)
		{
			return $arrMsg[0];
		}
		else if ($size == 2)
		{
			return $arrMsg[0] . sprintf(' %s ', $this->getTranslator()->_('AND')) . $arrMsg[1];
		}
		else if ($size > 2)
		{
			$lastItem = $arrMsg[$size - 1];
			array_pop($arrMsg);
			return implode(', ', $arrMsg) . sprintf(' %s ', $this->getTranslator()->_('AND')) . $lastItem;
		}
	}

	public function render(Zend_View_Interface $view = null)
	{
		if (!empty($this->_storeRow))
		{
			$this->_updatePreviousImage($this->_storeRow);
			$this->_updatePreviousCssFile($this->_storeRow);
		}
		return parent::render($view);
	}

	public function setDefaultFanpage($id_page)
	{
		$this->getElement(self::FANPAGE_NAME)->setValue(array($id_page));
	}

	public function setCancelUrl($url)
	{
		$this->_cancelUrl = $url;
	}
	public function setDownloadCssUrl($url)
	{
		$this->_downloadCssUrl = $url;
	}
	public function getDownloadCssUrl($url)
	{
		return $this->_downloadCssUrl;
	}
	
	public function getCancelUrl()
	{
		return $this->_cancelUrl;
	}

	public function getStore()
	{
		return $this->_storeRow;
	}

	public function hasStore()
	{
		return $this->_storeRow && !empty($this->_storeRow->id);
	}

}